package com.yuanduo_app.widget.record;

import android.media.MediaPlayer;
import android.widget.VideoView;

import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;

import com.yuanduo_app.bridge.DataModule;
import com.yuanduo_app.consts.RNEvent;
import com.yuanduo_app.manager.RNModuleManager;
import com.yuanduo_app.manager.VideoPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class VideoRnView extends SimpleViewManager<VideoView> {
    private static final int PLAY = 1;
    private static final int RESUME = 2;
    private static final int PAUSE = 3;
    private VideoPlayer mVideoPlayer;

    @NonNull
    @Override
    public String getName () {
        return "VideoRnView";
    }

    @NonNull
    @Override
    protected VideoView createViewInstance (@NonNull ThemedReactContext reactContext) {
        final VideoView videoView = new VideoView(reactContext);
        mVideoPlayer = new VideoPlayer(videoView);
        return videoView;
    }

    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap () {
        Map<String, Integer> map = new HashMap<>();
        map.put("play", PLAY);
        map.put("resume", RESUME);
        map.put("pause", PAUSE);
        return map;
    }

    @Override
    public void receiveCommand (@NonNull VideoView videoView, int commandId, @Nullable ReadableArray args) {
        super.receiveCommand(videoView, commandId, args);
        switch (commandId) {
            case PLAY:
                final ArrayList<Object> objects = args.toArrayList();
                Map<String, String> params = (Map<String, String>) objects.get(0);
                final String path = params.get("path");
                mVideoPlayer.play(path);
                mVideoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion (MediaPlayer mp) {
                        DataModule module = RNModuleManager.getInstance().getModule(DataModule.class);
                        if (module != null) {
                            module.sendEvent(RNEvent.VIDEO_PLAY_STATE, RNEvent.STOP);
                        }
                    }
                });
                break;
            case RESUME:
                mVideoPlayer.resume();
                break;
            case PAUSE:
                mVideoPlayer.pause();
                break;
            default:
                break;
        }
    }
}
